<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"chuangges.gitee.io","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"right","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="网络通信、Ajax 请求、跨域方案、页面交互">
<meta property="og:type" content="article">
<meta property="og:title" content="JS 实现页面的通信和交互">
<meta property="og:url" content="https://chuangges.gitee.io/2019/05/28/4-5-js%E4%BA%A4%E4%BA%92/index.html">
<meta property="og:site_name" content="闯哥要去流浪了">
<meta property="og:description" content="网络通信、Ajax 请求、跨域方案、页面交互">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://chuangges.gitee.io/images/web/OSI.png">
<meta property="article:published_time" content="2019-05-28T15:09:57.000Z">
<meta property="article:modified_time" content="2023-09-19T08:59:09.662Z">
<meta property="article:author" content="chuangges">
<meta property="article:tag" content="Javascript">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://chuangges.gitee.io/images/web/OSI.png">

<link rel="canonical" href="https://chuangges.gitee.io/2019/05/28/4-5-js%E4%BA%A4%E4%BA%92/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>JS 实现页面的通信和交互 | 闯哥要去流浪了</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="闯哥要去流浪了" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">闯哥要去流浪了</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">愿你岁月可回首，且以深情共白头</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://chuangges.gitee.io/2019/05/28/4-5-js%E4%BA%A4%E4%BA%92/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/chuang.png">
      <meta itemprop="name" content="chuangges">
      <meta itemprop="description" content="chuangge's blog.">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="闯哥要去流浪了">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          JS 实现页面的通信和交互
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-05-28 23:09:57" itemprop="dateCreated datePublished" datetime="2019-05-28T23:09:57+08:00">2019-05-28</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2023-09-19 16:59:09" itemprop="dateModified" datetime="2023-09-19T16:59:09+08:00">2023-09-19</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Javascript/" itemprop="url" rel="index"><span itemprop="name">Javascript</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>26k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>24 分钟</span>
            </span>
            <div class="post-description">网络通信、Ajax 请求、跨域方案、页面交互</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="一、网络通信"><a href="#一、网络通信" class="headerlink" title="一、网络通信"></a>一、网络通信</h1><h2 id="网络模型"><a href="#网络模型" class="headerlink" title="网络模型"></a>网络模型</h2><ul>
<li><strong>计算机网络</strong>：连接在一起的计算机和打印机、路由器、交换机等设备组成的系统，通过电缆和光纤等物理介质传输数据流并通过协议控制数据的传输和转换。数据传输的可靠性通过链路层和网络层的 <code>PPP 点对点协议</code> (基于 MAC&#x2F;IP 地址通过一台台直接相连的设备将数据传递到接收端) 和传输层的 <code>TCP 端对端协议</code> (在数据传输之前建立一条链路)。 </li>
<li>国际标准组织为计算机通信提出的 <strong>OSI 七层理论模型</strong>：<code>应用层</code> (计算机和应用的连接)、<code>表示层</code>、<code>会话层</code>、<code>传输层</code> (端口到端口的连接)、<code>网络层</code> (主机到主机的连接)、<code>链路层</code>、<code>物理层</code>。</li>
<li>针对网络各部分规定了通信标准和方法的 <strong>TCP&#x2F;IP 四层应用模型</strong>：<code>应用层</code> (HTTP 超文本传输、FTP 文本传输、DNS 域名、DHCP 动态主机配置、SSH 安全外壳、Telnet 远程登录)、<code>传输层</code> (TCP 传输控制、UDP 数据报文、SSL&#x2F;TLS 安全)、<code>网络层</code> (IP 标识网络设备的地址、ARP 地址解析、IGMP 组管理、ICMP 报文控制、RIP 路由信息、OSPF 分布式链路状态、BGP 边界网关)、<code>链路层</code> (PPP 点对点、ARQ 自动重传、CSMA&#x2F;CD 停止等待、IEEE 802.3 有线以太网封装刻录在网卡的硬件设备标识 MAC 地址并传输比特流)。</li>
</ul>
  <div align="center">
      <img src="" data-original="/images/web/OSI.png" alt="网络模型" width="100%">
  </div>


<h2 id="TCP-x2F-UDP-协议"><a href="#TCP-x2F-UDP-协议" class="headerlink" title="TCP&#x2F;UDP 协议"></a>TCP&#x2F;UDP 协议</h2><blockquote>
<p>两种协议都能够传输数据但区别是要不要提前建立连接，TCP 是面向连接的、可靠的、全双工 (双方都可以发送接收数据)、基于字节流的传输层协议，在传送数据前通过三次握手建立连接而保证了网络可靠性，常用于 HTTP、邮件、登录等。UDP 则是面向无连接的、不可靠的、非全双工 (一&#x2F;多对一&#x2F;多)、基于报文的传输层协议，不会建立连接也不会重发和收到响应，但是由于传输效率和实时性更好而应用于在线视频、在线语音、物联网设备等。　</p>
</blockquote>
  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// TCP 通讯程序：Client、Server</span></span><br><span class="line"><span class="keyword">var</span> net = <span class="built_in">require</span>(<span class="string">&quot;net&quot;</span>);</span><br><span class="line"><span class="keyword">var</span> client = net.<span class="title function_">connect</span>(<span class="number">3000</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;连接到服务器！&quot;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="keyword">let</span> n = <span class="number">3</span>;</span><br><span class="line"><span class="keyword">const</span> interval = <span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> msg = <span class="string">&quot;Time &quot;</span> + <span class="keyword">new</span> <span class="title class_">Date</span>().<span class="title function_">getTime</span>();</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;客户端发送: &quot;</span> + msg);</span><br><span class="line">    client.<span class="title function_">write</span>(msg);</span><br><span class="line">    <span class="keyword">if</span> (n-- === <span class="number">0</span>) &#123;</span><br><span class="line">        client.<span class="title function_">end</span>();</span><br><span class="line">        <span class="built_in">clearInterval</span>(interval);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;, <span class="number">500</span>);</span><br><span class="line">client.<span class="title function_">on</span>(<span class="string">&quot;end&quot;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;断开与服务器的连接&quot;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> net = <span class="built_in">require</span>(<span class="string">&quot;net&quot;</span>);</span><br><span class="line"><span class="keyword">var</span> server = net.<span class="title function_">createServer</span>(<span class="function">(<span class="params">connection</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;client connected&quot;</span>);</span><br><span class="line">    connection.<span class="title function_">on</span>(<span class="string">&quot;data&quot;</span>, <span class="function">(<span class="params">data</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;Server接收: &quot;</span> + data.<span class="title function_">toString</span>());</span><br><span class="line">    &#125;);</span><br><span class="line">    connection.<span class="title function_">on</span>(<span class="string">&quot;end&quot;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;客户端关闭连接&quot;</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">    connection.<span class="title function_">end</span>(<span class="string">&quot;Hello I am \r\n&quot;</span>);</span><br><span class="line">&#125;);</span><br><span class="line">server.<span class="title function_">listen</span>(<span class="number">3000</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;server is listening at 3000&quot;</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>


<h2 id="HTTP-协议"><a href="#HTTP-协议" class="headerlink" title="HTTP 协议"></a>HTTP 协议</h2><blockquote>
<p>TCP 通过建立连接而提供可靠的字节流形式的通信，HTTP 则基于 TCP 连接定义通信格式并负责具体的数据传输，具有单向请求和无状态等特点。HTTP 传输单位是请求&#x2F;响应报文，内部结构主要有 <code>请求行/响应行</code> (请求方法 + 请求地址 + 版本号 &#x2F; 版本号 + 状态码 + 状态原因)、<code>头部</code> (包含 header 并分为通用头 请求头 响应头 实体头)、<code>实体</code> (包含数据)。</p>
</blockquote>
  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// HTTP 爬虫访问百度首页</span></span><br><span class="line"><span class="keyword">const</span> net = <span class="built_in">require</span>(<span class="string">&quot;net&quot;</span>);</span><br><span class="line"><span class="keyword">const</span> createFormater = <span class="built_in">require</span>(<span class="string">&quot;./http/formater&quot;</span>);</span><br><span class="line"><span class="keyword">const</span> formater = <span class="title function_">createFormater</span>(<span class="string">&quot;request&quot;</span>);</span><br><span class="line"><span class="keyword">const</span> req = &#123;</span><br><span class="line">    <span class="attr">method</span>: <span class="string">&quot;GET&quot;</span>,</span><br><span class="line">    <span class="attr">url</span>: <span class="string">&quot;/&quot;</span>,</span><br><span class="line">    <span class="attr">version</span>: <span class="string">&quot;HTTP/1.1&quot;</span>,</span><br><span class="line">    <span class="attr">headers</span>: &#123; <span class="string">&quot;user-agent&quot;</span>: <span class="string">&quot;curl/7.71.1&quot;</span>, <span class="attr">accept</span>: <span class="string">&quot;*/*&quot;</span> &#125;,</span><br><span class="line">    <span class="attr">body</span>: <span class="string">&quot;&quot;</span>,</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">const</span> client = net.<span class="title function_">connect</span>(<span class="number">80</span>, <span class="string">&quot;www.baidu.com&quot;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;连接到服务器！&quot;</span>);</span><br><span class="line">    client.<span class="title function_">write</span>(formater.<span class="title function_">format</span>(req));</span><br><span class="line">&#125;);</span><br><span class="line">client.<span class="title function_">on</span>(<span class="string">&quot;data&quot;</span>, <span class="keyword">function</span> (<span class="params">data</span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(data.<span class="title function_">toString</span>());</span><br><span class="line">    client.<span class="title function_">end</span>();</span><br><span class="line">&#125;);</span><br><span class="line">client.<span class="title function_">on</span>(<span class="string">&quot;end&quot;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;断开与服务器的连接&quot;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 支持 Chrome 访问的 HTTP 服务器：localhost:3000</span></span><br><span class="line"><span class="keyword">const</span> net = <span class="built_in">require</span>(<span class="string">&quot;net&quot;</span>);</span><br><span class="line"><span class="keyword">const</span> createFormater = <span class="built_in">require</span>(<span class="string">&quot;./http/formater&quot;</span>);</span><br><span class="line"><span class="keyword">const</span> formater = <span class="title function_">createFormater</span>(<span class="string">&quot;response&quot;</span>);</span><br><span class="line"><span class="keyword">const</span> res = &#123;</span><br><span class="line">    <span class="attr">version</span>: <span class="string">&quot;HTTP/1.1&quot;</span>,</span><br><span class="line">    <span class="attr">status</span>: <span class="string">&quot;200&quot;</span>,</span><br><span class="line">    <span class="attr">message</span>: <span class="string">&quot;OK&quot;</span>,</span><br><span class="line">    <span class="attr">headers</span>: &#123;</span><br><span class="line">        <span class="attr">date</span>: <span class="string">&quot;Sat, 04 Dec 2021 14&quot;</span>,</span><br><span class="line">        <span class="attr">connection</span>: <span class="string">&quot;keep-alive&quot;</span>,</span><br><span class="line">        <span class="string">&quot;keep-alive&quot;</span>: <span class="string">&quot;timeout=5&quot;</span>,</span><br><span class="line">        <span class="comment">// &quot;content-length&quot;: &quot;19&quot;,</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">body</span>: <span class="string">&quot;&lt;h1&gt; Hello HTTP&lt;h1&gt;&quot;</span>,</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">const</span> server = net.<span class="title function_">createServer</span>(<span class="keyword">function</span> (<span class="params">connection</span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;client connected&quot;</span>);</span><br><span class="line">    connection.<span class="title function_">on</span>(<span class="string">&quot;data&quot;</span>, <span class="function">(<span class="params">data</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(data.<span class="title function_">toString</span>());</span><br><span class="line">    &#125;);</span><br><span class="line">    connection.<span class="title function_">on</span>(<span class="string">&quot;end&quot;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;客户端关闭连接&quot;</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">    connection.<span class="title function_">end</span>(formater.<span class="title function_">format</span>(res));</span><br><span class="line">&#125;);</span><br><span class="line">server.<span class="title function_">listen</span>(<span class="number">3000</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;server is listening&quot;</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>


<h2 id="Socket-接口"><a href="#Socket-接口" class="headerlink" title="Socket 接口"></a>Socket 接口</h2>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 基于 TCP/IP 协议封装的对外编程接口，不同语言都有对应库</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Nodejs 服务端</span></span><br><span class="line"><span class="keyword">const</span> net = <span class="built_in">require</span>(<span class="string">&#x27;net&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> server = net.<span class="title function_">createServer</span>();</span><br><span class="line">server.<span class="title function_">on</span>(<span class="string">&#x27;connection&#x27;</span>, <span class="function">(<span class="params">client</span>) =&gt;</span> &#123;</span><br><span class="line">    client.<span class="title function_">write</span>(<span class="string">&#x27;Hi!\n&#x27;</span>);    <span class="comment">// 服务端向客户端输出信息，使用 write()</span></span><br><span class="line">    client.<span class="title function_">write</span>(<span class="string">&#x27;Bye!\n&#x27;</span>);</span><br><span class="line">    <span class="comment">//client.end();           // 服务端结束该次会话</span></span><br><span class="line">&#125;);</span><br><span class="line">server.<span class="title function_">listen</span>(<span class="number">9000</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// Nodejs 客户端</span></span><br><span class="line"><span class="keyword">const</span> client = <span class="keyword">new</span> net.<span class="title class_">Socket</span>();</span><br><span class="line">client.<span class="title function_">connect</span>(<span class="number">9000</span>, <span class="string">&#x27;127.0.0.1&#x27;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line"></span><br><span class="line">&#125;);</span><br><span class="line">client.<span class="title function_">on</span>(<span class="string">&#x27;data&#x27;</span>, <span class="function">(<span class="params">chunk</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;data&#x27;</span>, chunk.<span class="title function_">toString</span>())</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// Socket 长连接：在一个 TCP 连接上连续发送多个数据包，可通过计时器实现</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Socket 连接池：维护着一定数量 Socket 长连接的集合。它能自动检测 Socket</span></span><br><span class="line"><span class="comment">// 长连接的有效性，剔除无效的连接并补充连接池中长连接的数量。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Nodejs Socket 连接池 generic-pool 模块的源码</span></span><br><span class="line"><span class="keyword">const</span> net = <span class="built_in">require</span>(<span class="string">&#x27;net&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> genericPool = <span class="built_in">require</span>(<span class="string">&#x27;generic-pool&#x27;</span>);</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">createPool</span>(<span class="params">conifg</span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> options = <span class="title class_">Object</span>.<span class="title function_">assign</span>(&#123;</span><br><span class="line">        <span class="attr">fifo</span>: <span class="literal">true</span>,                          <span class="comment">// 是否优先使用老的资源</span></span><br><span class="line">        <span class="attr">priorityRange</span>: <span class="number">1</span>,                    <span class="comment">// 优先级</span></span><br><span class="line">        <span class="attr">testOnBorrow</span>: <span class="literal">true</span>,                  <span class="comment">// 是否开启获取验证</span></span><br><span class="line">        <span class="attr">acquireTimeoutMillis</span>: <span class="number">10</span> * <span class="number">1000</span>,     <span class="comment">// 获取的超时时间</span></span><br><span class="line">        <span class="attr">autostart</span>: <span class="literal">true</span>,                     <span class="comment">// 自动初始化和释放调度启用</span></span><br><span class="line">        <span class="attr">min</span>: <span class="number">10</span>,                             <span class="comment">// 连接池保持的长连接最小数量</span></span><br><span class="line">        <span class="attr">max</span>: <span class="number">0</span>,                              <span class="comment">// 最大连接池保持的长连接数量</span></span><br><span class="line">        <span class="attr">evictionRunIntervalMillis</span>: <span class="number">0</span>,        <span class="comment">// 资源释放检验间隔检查</span></span><br><span class="line">        <span class="attr">numTestsPerEvictionRun</span>: <span class="number">3</span>,           <span class="comment">// 每次释放资源数量</span></span><br><span class="line">        <span class="attr">softIdleTimeoutMillis</span>: -<span class="number">1</span>,           <span class="comment">// 可用的&gt;min 且空闲时间时释放</span></span><br><span class="line">        <span class="attr">idleTimeoutMillis</span>: <span class="number">30000</span>             <span class="comment">// 强制释放</span></span><br><span class="line">        <span class="attr">maxWaitingClients</span>: <span class="number">50</span>                <span class="comment">// 最大等待</span></span><br><span class="line">    &#125;, conifg.<span class="property">options</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> factory = &#123;</span><br><span class="line">        <span class="attr">create</span>: <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">                <span class="keyword">let</span> socket = <span class="keyword">new</span> net.<span class="title class_">Socket</span>();</span><br><span class="line">                socket.<span class="title function_">setKeepAlive</span>(<span class="literal">true</span>);</span><br><span class="line">                socket.<span class="title function_">connect</span>(conifg.<span class="property">port</span>, conifg.<span class="property">host</span>);</span><br><span class="line">                <span class="comment">// TODO 心跳包的处理逻辑：先 end 再 close</span></span><br><span class="line">                socket.<span class="title function_">on</span>(<span class="string">&#x27;connect&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">                    <span class="title function_">resolve</span>(socket);</span><br><span class="line">                &#125;);</span><br><span class="line">                socket.<span class="title function_">on</span>(<span class="string">&#x27;close&#x27;</span>, <span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">                &#125;);</span><br><span class="line">                socket.<span class="title function_">on</span>(<span class="string">&#x27;error&#x27;</span>, <span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">                    <span class="title function_">reject</span>(err);</span><br><span class="line">                &#125;);</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="comment">// 销毁连接：不会触发 end，第一次触发 close，有 message 则触发 error</span></span><br><span class="line">        <span class="attr">destroy</span>: <span class="keyword">function</span> (<span class="params">socket</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> &#123;</span><br><span class="line">                socket.<span class="title function_">destroy</span>();</span><br><span class="line">                <span class="title function_">resolve</span>();</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="comment">// 获取资源池校验资源有效性</span></span><br><span class="line">        <span class="attr">validate</span>: <span class="keyword">function</span> (<span class="params">socket</span>) &#123; </span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> &#123;</span><br><span class="line">                <span class="keyword">if</span> (!socket.<span class="property">destroyed</span> &amp;&amp; </span><br><span class="line">                    socket.<span class="property">readable</span> &amp;&amp; </span><br><span class="line">                    socket.<span class="property">writable</span>) &#123;</span><br><span class="line">                    <span class="keyword">return</span> <span class="title function_">resolve</span>(<span class="literal">true</span>);</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="keyword">return</span> <span class="title function_">resolve</span>(<span class="literal">false</span>);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">const</span> pool = genericPool.<span class="title function_">createPool</span>(factory, options);</span><br><span class="line">    pool.<span class="title function_">on</span>(<span class="string">&#x27;factoryCreateError&#x27;</span>, <span class="function">(<span class="params">err</span>) =&gt;</span> &#123;  <span class="comment">// 新建长连接出错则返回错误</span></span><br><span class="line">        <span class="keyword">const</span> clientResourceRequest = pool.<span class="property">waitClientsQueue</span>.<span class="title function_">dequeue</span>();</span><br><span class="line">        <span class="keyword">if</span> (clientResourceRequest) &#123;</span><br><span class="line">            clientResourceRequest.<span class="title function_">reject</span>(err);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">return</span> pool;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h1 id="二、Ajax-请求"><a href="#二、Ajax-请求" class="headerlink" title="二、Ajax 请求"></a>二、Ajax 请求</h1><blockquote>
<p>异步网络请求，在页面不跳转不刷新的情况下实现局部加载，减少了数据传输量。</p>
</blockquote>
<h2 id="主要特点"><a href="#主要特点" class="headerlink" title="主要特点"></a>主要特点</h2><div style="text-indent: 2em">在用户和服务器之间加了―个中间层 (Ajax 引擎)，通过 XmlHttpRequest 对象来向服务器发异步请求并获取数据，然后通过 js 操作 DOM 而更新页面，这样就让用户操作与服务器响应实现了异步化，从而 js 可以及时向服务器提出请求和处理响应而不阻塞用户，达到无刷新的效果。注意如果出现乱码问题就是因为编码格式冲突，发送中文数据时通过 encodeURI() 编码，接收中文数据时通过 decodeURI() 解码即可。</div>

<ul>
<li><strong>优点</strong><ul>
<li>使用异步方式与服务器通信，响应速度更快。</li>
<li>基于标准化的并被广泛支持的技术，不需要下载插件或者小程序。</li>
<li>页面无刷新，在页面内与服务器通信，减少用户等待时间，增强了用户体验。</li>
<li>可以把一些原本服务器的工作转接到客户端，利用客户端闲置的能力来处理，减轻了服务器和带宽的负担，节约空间和宽带租用成本。</li>
</ul>
</li>
<li><strong>缺点</strong><ul>
<li>对搜索引擎的支持比较弱。</li>
<li>可能会影响程序中的异常处理机制。</li>
<li>无法进行操作的后退，即不支持浏览器的页面后退。</li>
<li>安全问题，对一些网站攻击，比如 csrf、xxs、sql 注入等不能很好地防御。</li>
</ul>
</li>
</ul>
<h2 id="重点注意"><a href="#重点注意" class="headerlink" title="重点注意"></a>重点注意</h2><h3 id="请求方式"><a href="#请求方式" class="headerlink" title="请求方式"></a>请求方式</h3><ol>
<li><strong>区别</strong><br>* method：<code>GET、POST</code>。<br>* 请求头：POST 发送数据时必须设置。<br>* 安全性：GET 请求时暴露参数数据，安全性较低。<br>* 长度限制：GET 有长度限制，不适合发送大量数据。<br>* 请求缓存：GET 请求可以被缓存和保存，而 POST 请求不能。<br>* 参数位置：<code>url?参数=值&amp;参数=值、xhr.send(&quot;参数=值&amp;参数=值&quot;)</code>。</li>
<li><strong>场景</strong><br>* GET：安全性要求不高时，从服务器获取数据。<br>* POST：对于大量数据、密码数据等，提交到服务器处理。</li>
</ol>
<h3 id="数据格式"><a href="#数据格式" class="headerlink" title="数据格式"></a>数据格式</h3><ol>
<li><strong>JSON</strong>：处理大量数据的规范格式。<br>* 对象转字符串：<code>JSON.stringify(json_obj)</code><br>* 字符串转对象：<code>JSON.parse(json_str) / eval(&#39;(&#39;+json_str+&#39;)&#39;)</code><br>* eval：不推荐使用，因为它会把 js 数据而不只是 json_str 都转为 json 对象。</li>
<li><strong>FormData</strong>：处理包括图片和文件的表单数据并通过 post 方式发送到服务端。</li>
</ol>
  <figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">id</span>=<span class="string">&quot;form&quot;</span> <span class="attr">method</span>=<span class="string">&quot;post&quot;</span> <span class="attr">enctype</span>=<span class="string">&quot;multipart/form-data&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;file&quot;</span> <span class="attr">name</span>=<span class="string">&quot;file&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">// 1、实例一个空 FormData 对象之后 append 键值对</span></span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">var</span> formdata = <span class="keyword">new</span> <span class="title class_">FormData</span>() </span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">var</span> file = <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&quot;file&quot;</span>).<span class="property">files</span>[<span class="number">0</span>]</span></span><br><span class="line"><span class="language-javascript">    formData.<span class="title function_">append</span>(<span class="string">&#x27;file&#x27;</span>, file)</span></span><br><span class="line"><span class="language-javascript">                              </span></span><br><span class="line"><span class="language-javascript">    <span class="comment">// 2、form元素对象 作为参数传入  </span></span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">var</span> form = <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&quot;form&quot;</span>)</span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">var</span> formdata = <span class="keyword">new</span> <span class="title class_">FormData</span>(form);                          </span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">// 3、getFormData 方法</span></span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">var</span> formobj =  <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&quot;form&quot;</span>);</span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">var</span> formdata = formobj.<span class="title function_">getFormData</span>()</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">// 其它 API：has、getAll、forEach</span></span></span><br><span class="line"><span class="language-javascript">    formdata.<span class="title function_">delete</span>(<span class="string">&quot;file&quot;</span>)   </span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">var</span> file = formdata.<span class="title function_">get</span>(<span class="string">&quot;file&quot;</span>)</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span>       </span><br></pre></td></tr></table></figure>


<h3 id="请求体类型"><a href="#请求体类型" class="headerlink" title="请求体类型"></a>请求体类型</h3><blockquote>
<p>ContentType，告诉服务器发送数据的格式</p>
</blockquote>
<ul>
<li><code>application/x-www-form-urlencoded</code>：jquery ajax 默认，查询字符串格式。</li>
<li><code>multipart/form-data</code>：常用于表单上传文件，设置 form enctype 为该类型。</li>
<li><code>application/json</code>：axios 默认类型，使用 json 格式的数据。</li>
</ul>
<h2 id="简单使用"><a href="#简单使用" class="headerlink" title="简单使用"></a>简单使用</h2><h3 id="原生写法"><a href="#原生写法" class="headerlink" title="原生写法"></a>原生写法</h3>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1、创建 XMLHttpRequest 对象：用来和服务器交换数据的 js 内置对象</span></span><br><span class="line"><span class="keyword">var</span> xhr;</span><br><span class="line"><span class="keyword">if</span>(<span class="title class_">XMLHttpRequest</span>)&#123;</span><br><span class="line">    xhr = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();   <span class="comment">// w3c 标准</span></span><br><span class="line">&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">    xhr = <span class="keyword">new</span> <span class="title class_">ActiveXObject</span>(<span class="string">&#x27;Microsoft.XMLHTTP&#x27;</span>)  <span class="comment">// IE6、IE5</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 2、连接服务器和发送请求</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// GET </span></span><br><span class="line">xhr.<span class="title function_">open</span>(<span class="string">&#x27;GET&#x27;</span>, url?参数=值, <span class="literal">true</span>);   <span class="comment">// true 表示请求异步处理</span></span><br><span class="line">xhr.<span class="title function_">send</span>();    </span><br><span class="line"></span><br><span class="line"><span class="comment">// POST 必须设置请求头</span></span><br><span class="line">xhr.<span class="title function_">open</span>(<span class="string">&quot;POST&quot;</span>, url, <span class="literal">true</span>);   </span><br><span class="line">xhr.<span class="title function_">setRequestHeader</span>(<span class="string">&quot;Content-type&quot;</span>, <span class="string">&quot;application/x-www-form-urlencoded&quot;</span>);</span><br><span class="line">xhr.<span class="title function_">send</span>(<span class="string">&quot;参数=值&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 3、监听回调函数状态和处理响应数据</span></span><br><span class="line">xhr.<span class="property">onreadystatechange</span> = <span class="keyword">function</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="comment">// 判断响应是否接收完成、服务器是否成功处理请求</span></span><br><span class="line">    <span class="keyword">if</span>(xhr.<span class="property">readyState</span> == <span class="number">4</span> &amp;&amp; xhr.<span class="property">status</span> ==<span class="number">200</span>)&#123;</span><br><span class="line">        show.<span class="property">innerHTML</span> = xhr.<span class="property">responseText</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h3 id="Ajax-封装"><a href="#Ajax-封装" class="headerlink" title="Ajax 封装"></a>Ajax 封装</h3>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">requestUrl</span>(<span class="params">url, type, data, callback, error, <span class="keyword">async</span></span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> <span class="keyword">async</span> = (<span class="keyword">async</span> == <span class="literal">null</span> || </span><br><span class="line">                <span class="keyword">async</span>.<span class="title function_">toString</span>() == <span class="string">&quot;&quot;</span> || </span><br><span class="line">                <span class="title function_">typeof</span>(<span class="keyword">async</span>) == <span class="string">&quot;undefined&quot;</span>) ? <span class="literal">true</span> : !!<span class="keyword">async</span>;</span><br><span class="line">    $.<span class="title function_">ajax</span>(&#123;</span><br><span class="line">        <span class="attr">url</span>: url,</span><br><span class="line">        <span class="attr">method</span>: type,</span><br><span class="line">        <span class="attr">async</span>: <span class="keyword">async</span>,</span><br><span class="line">        <span class="attr">data</span>: data</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">done</span>(<span class="keyword">function</span>(<span class="params">data</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (_data.<span class="property">status</span> == <span class="number">200</span>) &#123;</span><br><span class="line">            <span class="title function_">callback</span>(_data.<span class="property">data</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="title function_">typeof</span>(error) == <span class="string">&#x27;function&#x27;</span>) &#123;</span><br><span class="line">                <span class="title function_">error</span>(_data)</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="title function_">alert</span>(_data.<span class="property">data</span>.<span class="property">errMsg</span>)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">fail</span>(<span class="keyword">function</span>(<span class="params"> jqXHR, textStatus </span>) &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">            <span class="title function_">requestUrl</span>(url, type, data, callback, error, <span class="keyword">async</span>);</span><br><span class="line">        &#125;, <span class="number">1000</span>);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h3 id="JQuery-写法"><a href="#JQuery-写法" class="headerlink" title="JQuery 写法"></a>JQuery 写法</h3>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">$.<span class="title function_">get</span>(url?参数=值, calback)</span><br><span class="line"></span><br><span class="line">$.<span class="title function_">post</span>(url, &#123;参数：值&#125;, callback)</span><br><span class="line"></span><br><span class="line">$.<span class="title function_">ajax</span>(&#123;</span><br><span class="line">    <span class="attr">type</span>:       <span class="comment">// 数据的提交方式：get、post</span></span><br><span class="line">    <span class="attr">url</span>:        <span class="comment">// 请求地址</span></span><br><span class="line">    <span class="attr">async</span>:      <span class="comment">// 是否支持异步刷新，默认 true</span></span><br><span class="line">    <span class="attr">data</span>:       <span class="comment">// 需要提交的数据</span></span><br><span class="line">    <span class="attr">dataType</span>:   <span class="comment">// 服务器返回数据的类型，html、json, jsonp 等</span></span><br><span class="line">    <span class="attr">success</span>: <span class="keyword">function</span>(<span class="params">data</span>)&#123; &#125;  <span class="comment">// 请求成功后的回调函数 </span></span><br><span class="line">    <span class="attr">error</span>: <span class="keyword">function</span>(<span class="params">data</span>)&#123;&#125;     <span class="comment">// 请求失败后的回调函数 </span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>


<h2 id="Token-令牌"><a href="#Token-令牌" class="headerlink" title="Token 令牌"></a>Token 令牌</h2><blockquote>
<p>遵从 oauth2.0 规范的授权令牌，它是一种身份&#x2F;权限的认证方式。</p>
</blockquote>
<ol>
<li>应用<br>* 客户端登录等首次请求发送时，服务端根据算法和编码方式生成后返回。<br>* 客户端再次发起请求时，服务端验证通过后返回请求数据，否则失败。</li>
<li>优势<br>* 可以避免 CSRF 攻击。<br>* 完全由应用管理，可以避开同源策略。<br>* 可扩展性强(不用存储)，还可用于 APP。<br>* 可以是无状态的，可以在多个服务间共享。</li>
</ol>
<h1 id="三、跨域方案"><a href="#三、跨域方案" class="headerlink" title="三、跨域方案"></a>三、跨域方案</h1>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">浏览器的同源策略：浏览器出于安全方面的考虑而只允许与本域下的接口交互，</span><br><span class="line">不同源的脚本在没有明确授权时不能读写对方资源，这样阻止恶意修改和攻击但</span><br><span class="line">也产生了跨域问题，浏览器可以设置开启跨域但不是一个好方案。</span><br><span class="line"></span><br><span class="line">同源条件：protocol（协议）、domain（域名）、port（端口）三者一致。</span><br><span class="line"></span><br><span class="line">协议      域名              端口  路径    参数            锚点</span><br><span class="line"><span class="attr">http</span>:<span class="comment">//  www.example.com  :80   /home  ?name=a&amp;age=20  #app</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">开启跨域模式：通过 <span class="title class_">Chrome</span> <span class="variable constant_">CORS</span> 插件或手动设置，但这种方式不建议使用。</span><br><span class="line"></span><br><span class="line">浏览器跨域原因：浏览器端允许打开多个页面，但页面之间的需要统一规范来约定，</span><br><span class="line">跨域规范就是通过限制不同源的请求、限制 dom 操作而实现安全性。</span><br></pre></td></tr></table></figure>

<h2 id="CORS-跨域资源共享"><a href="#CORS-跨域资源共享" class="headerlink" title="CORS 跨域资源共享"></a>CORS 跨域资源共享</h2><blockquote>
<p>一个 W3C 标准&#x2F;机制，Web 应用使用自定义 HTTP 头部告诉浏览器向跨域服务器发起 HTTP 请求，注意低版本浏览器不支持。</p>
</blockquote>
<ul>
<li><strong>简单请求</strong>：不会触发 CORS 预检请求。条件如下：<ul>
<li>请求方法：GET&#x2F;HEAD&#x2F;POST。</li>
<li>人为设置以下之外的请求头：Accept、Accept-Language、Content-Language、Content-Type、DPR、Downlink、Save-Data、Viewport-Width、Width。</li>
<li>Content-Type：text&#x2F;plain、multipart&#x2F;form-data、application&#x2F;x-www-form-urlencoded。</li>
<li>请求中的对象 XMLHttpRequest.upload 没有注册任何事件监听器。</li>
<li>请求中没有使用 ReadableStream 对象。</li>
</ul>
</li>
<li><strong>非简单请求</strong>：除以上情况之外。</li>
<li><strong>Node 解决方案</strong></li>
</ul>
  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 简单请求</span></span><br><span class="line">axios.<span class="title function_">get</span>(<span class="string">&quot;http://127.0.0.1:8080/api/corslist&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 非简单请求</span></span><br><span class="line">axios.<span class="title function_">get</span>(<span class="string">&quot;http://127.0.0.1:8080/api/corslist&quot;</span>, &#123; <span class="attr">header</span>: &#123; <span class="attr">cc</span>: <span class="string">&quot;xxx&quot;</span> &#125; &#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// Node 原生方式</span></span><br><span class="line">app.<span class="title function_">use</span>(<span class="keyword">async</span> (ctx, next) =&gt; &#123;</span><br><span class="line">    ctx.<span class="title function_">set</span>(<span class="string">&quot;Access-Control-Allow-Origin&quot;</span>, ctx.<span class="property">headers</span>.<span class="property">origin</span>);</span><br><span class="line">    ctx.<span class="title function_">set</span>(<span class="string">&quot;Access-Control-Allow-Credentials&quot;</span>, <span class="literal">true</span>);</span><br><span class="line">    ctx.<span class="title function_">set</span>(<span class="string">&quot;Access-Control-Request-Method&quot;</span>, <span class="string">&quot;PUT,POST,GET,DELETE,OPTIONS&quot;</span>);</span><br><span class="line">    ctx.<span class="title function_">set</span>(</span><br><span class="line">        <span class="string">&quot;Access-Control-Allow-Headers&quot;</span>,</span><br><span class="line">        <span class="string">&quot;Origin, X-Requested-With, Content-Type, Accept, cc&quot;</span></span><br><span class="line">    );</span><br><span class="line">    <span class="keyword">if</span> (ctx.<span class="property">method</span> === <span class="string">&quot;OPTIONS&quot;</span>) &#123;</span><br><span class="line">        ctx.<span class="property">status</span> = <span class="number">204</span>;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">await</span> <span class="title function_">next</span>();</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// Node 第三方中间件</span></span><br><span class="line"><span class="keyword">const</span> cors = <span class="built_in">require</span>(<span class="string">&quot;koa-cors&quot;</span>);</span><br><span class="line">app.<span class="title function_">use</span>(<span class="title function_">cors</span>());</span><br></pre></td></tr></table></figure>


<h2 id="Node-正向代理"><a href="#Node-正向代理" class="headerlink" title="Node 正向代理"></a>Node 正向代理</h2><blockquote>
<p>利用服务端请求不会跨域的特性，让接口和当前站点同域。</p>
</blockquote>
<h3 id="cli-工具"><a href="#cli-工具" class="headerlink" title="cli 工具"></a>cli 工具</h3>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 前端请求：浏览器跨域请求默认不传递 cookie，可设置 withCredentials</span></span><br><span class="line">axios.<span class="property">defaults</span>.<span class="property">withCredentials</span> = <span class="literal">true</span>;</span><br><span class="line">axios.<span class="title function_">get</span>(<span class="string">&quot;/api/corslist&quot;</span>)</span><br><span class="line">axios.<span class="title function_">post</span>(<span class="string">&quot;/api/login&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 服务端</span></span><br><span class="line"><span class="comment">// Webpack 4.x</span></span><br><span class="line"><span class="attr">proxy</span>: &#123;</span><br><span class="line">    <span class="string">&quot;/api&quot;</span>: &#123; <span class="attr">target</span>: <span class="string">&quot;http://localhost:8080&quot;</span> &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// Vue-cli：版本 2.x 使用 proxyTable，版本 3.0 使用 proxy</span></span><br><span class="line"><span class="comment">// 配置一个代理</span></span><br><span class="line"><span class="comment">// proxy: &#x27;http://localhost:8000&#x27;  </span></span><br><span class="line"><span class="comment">// 配置多个代理：</span></span><br><span class="line"><span class="attr">proxy</span>: &#123;                             </span><br><span class="line">    <span class="string">&quot;/api&quot;</span>: &#123;     <span class="comment">// 请求地址</span></span><br><span class="line">        <span class="attr">target</span>: <span class="string">&quot;http://172.16.12:70&quot;</span>,  <span class="comment">// 实际映射的目标地址</span></span><br><span class="line">        <span class="attr">changeOrigin</span>: <span class="literal">true</span>,             <span class="comment">// 是否跨域</span></span><br><span class="line">        <span class="attr">ws</span>: <span class="literal">true</span>,                       <span class="comment">// websocket 支持</span></span><br><span class="line">        <span class="attr">secure</span>: <span class="literal">false</span>,                  <span class="comment">// https 需开启</span></span><br><span class="line">        <span class="attr">pathRewrite</span>:&#123; <span class="string">&#x27;^/api&#x27;</span>: <span class="string">&#x27;&#x27;</span> &#125;     <span class="comment">// 重定向</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// Parcel (2.x)</span></span><br><span class="line">.<span class="property">proxyrc</span>&#123;  </span><br><span class="line">    <span class="string">&quot;/api&quot;</span>: &#123;  <span class="string">&quot;target&quot;</span>: <span class="string">&quot;http://localhost:8080&quot;</span> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="cors-anywhere"><a href="#cors-anywhere" class="headerlink" title="cors-anywhere"></a>cors-anywhere</h3><blockquote>
<p>CORS 标头被添加到代理请求的 NodeJS 代理库，无法专递 cookie 而可能因为不太安全。</p>
</blockquote>
  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 前端请求</span></span><br><span class="line">axios.<span class="property">defaults</span>.<span class="property">withCredentials</span> = <span class="literal">true</span>;</span><br><span class="line">axios.<span class="title function_">get</span>(<span class="string">&quot;http://127.0.0.1:7777/http://127.0.0.1:8080/api/corslist&quot;</span>)</span><br><span class="line">axios.<span class="title function_">post</span>(<span class="string">&quot;http://127.0.0.1:7777/http://127.0.0.1:8080/api/login&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 服务端</span></span><br><span class="line"><span class="keyword">var</span> host = process.<span class="property">env</span>.<span class="property">HOST</span> || <span class="string">&quot;0.0.0.0&quot;</span>;</span><br><span class="line"><span class="keyword">var</span> port = process.<span class="property">env</span>.<span class="property">PORT</span> || <span class="number">7777</span>;</span><br><span class="line"><span class="keyword">var</span> cors_proxy = <span class="built_in">require</span>(<span class="string">&quot;cors-anywhere&quot;</span>);</span><br><span class="line">cors_proxy</span><br><span class="line">.<span class="title function_">createServer</span>(&#123;    </span><br><span class="line">    <span class="attr">originWhitelist</span>: [],</span><br><span class="line">    <span class="attr">requireHeader</span>: [<span class="string">&quot;origin&quot;</span>, <span class="string">&quot;x-requested-with&quot;</span>],    </span><br><span class="line">    <span class="attr">removeHeaders</span>: [<span class="string">&quot;cookie&quot;</span>, <span class="string">&quot;cookie2&quot;</span>]  </span><br><span class="line">&#125;)  </span><br><span class="line">.<span class="title function_">listen</span>(port, host, <span class="keyword">function</span>(<span class="params"></span>) &#123;    </span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;Running CORS Anywhere on &quot;</span> + host + <span class="string">&quot;:&quot;</span> + port);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h3 id="charles"><a href="#charles" class="headerlink" title="charles"></a>charles</h3><blockquote>
<p>一个测试、开发的神器，本质是请求的拦截与代理，代码。</p>
</blockquote>
  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 前端请求</span></span><br><span class="line">axios.<span class="property">defaults</span>.<span class="property">withCredentials</span> = <span class="literal">true</span>;</span><br><span class="line">axios.<span class="title function_">get</span>(<span class="string">&quot;/api/corslist&quot;</span>)</span><br><span class="line">axios.<span class="title function_">post</span>(<span class="string">&quot;/api/login&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 服务器</span></span><br><span class="line">router.<span class="title function_">get</span>(<span class="string">&quot;/api/corslist&quot;</span>, <span class="keyword">async</span> ctx =&gt; &#123;</span><br><span class="line">    ctx.<span class="property">body</span> = &#123; <span class="attr">data</span>: [&#123; <span class="attr">name</span>: <span class="string">&quot;闯哥的笔记&quot;</span> &#125;] &#125;;</span><br><span class="line">&#125;);</span><br><span class="line">router.<span class="title function_">post</span>(<span class="string">&quot;/api/login&quot;</span>, <span class="keyword">async</span> ctx =&gt; &#123;</span><br><span class="line">    ctx.<span class="property">cookies</span>.<span class="title function_">set</span>(<span class="string">&quot;token&quot;</span>, token, &#123; <span class="attr">expires</span>: <span class="keyword">new</span> <span class="title class_">Date</span>() &#125;)</span><br><span class="line">    ctx.<span class="property">body</span> = &#123;  <span class="attr">msg</span>: <span class="string">&quot;成功&quot;</span>, <span class="attr">code</span>: <span class="number">0</span> &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h2 id="Nginx-反向代理"><a href="#Nginx-反向代理" class="headerlink" title="Nginx 反向代理"></a>Nginx 反向代理</h2>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 配置</span></span><br><span class="line">server &#123;</span><br><span class="line">    listen      <span class="number">80</span>;         <span class="comment">// 监听端口</span></span><br><span class="line">    server_name <span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>;  <span class="comment">// 监听地址</span></span><br><span class="line">    location /api &#123;         <span class="comment">// 重定向地址</span></span><br><span class="line">        proxy_pass <span class="attr">http</span>:<span class="comment">//localhost:8080;</span></span><br><span class="line">    &#125;        </span><br><span class="line">    location / &#123;            <span class="comment">// 根目录地址    </span></span><br><span class="line">        proxy_pass <span class="attr">http</span>:<span class="comment">//localhost:8000;</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 启动、重启命令</span></span><br><span class="line">sudo nginx</span><br><span class="line">sudo nginx -s reload</span><br><span class="line"></span><br><span class="line"><span class="comment">// 前后端代码同上 charles</span></span><br></pre></td></tr></table></figure>


<h2 id="JSONP"><a href="#JSONP" class="headerlink" title="JSONP"></a>JSONP</h2><blockquote>
<p>利用 script 标签没有跨域限制的特性来实现跨域读取数据等，是一种非强制性协议而非新技术，也和 json、ajax 没有关系。</p>
</blockquote>
<ol>
<li>定义数据处理函数：<code>var handler = function(data)&#123; &#125;</code>。</li>
<li>创建 script 标签，src 的地址设置为 <code>url?callback=handler</code>。</li>
<li>服务端在收到请求后，解析参数并返回数据，输出 fun(data) 字符串。</li>
<li>fun(data) 会放到 script 标签中作为 js 执行，即此时会调用函数。</li>
</ol>
  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 后端实现</span></span><br><span class="line">app.<span class="title function_">use</span>(<span class="keyword">async</span> (ctx, next) =&gt; &#123;</span><br><span class="line">    <span class="keyword">if</span> (ctx.<span class="property">path</span> === <span class="string">&quot;/api/jsonp&quot;</span>) &#123;</span><br><span class="line">        <span class="keyword">const</span> &#123; cb, msg &#125; = ctx.<span class="property">query</span>;</span><br><span class="line">        ctx.<span class="property">body</span> = <span class="string">`<span class="subst">$&#123;cb&#125;</span>(<span class="subst">$&#123;<span class="built_in">JSON</span>.stringify(&#123; msg &#125;)&#125;</span>)`</span>;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line">app.<span class="title function_">listen</span>(<span class="number">8080</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 普通 js</span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span><span class="language-javascript">  </span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    <span class="variable language_">window</span>.<span class="property">handler</span> = <span class="keyword">function</span>(<span class="params">res</span>) &#123;  <span class="variable language_">console</span>.<span class="title function_">log</span>(res); &#125;;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;http://localhost:8080/api/jsonp?msg=hello&amp;callback=handler&quot;</span>  </span></span></span><br><span class="line"><span class="tag"><span class="language-xml"><span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">// jQuery Ajax</span></span><br><span class="line">$.<span class="title function_">ajax</span>(&#123;</span><br><span class="line">    <span class="attr">type</span>: <span class="string">&quot;get&quot;</span>,</span><br><span class="line">    <span class="attr">async</span>: <span class="literal">false</span>,</span><br><span class="line">    <span class="attr">url</span>: <span class="string">&quot;http://localhost:8080/api/jsonp&quot;</span>,</span><br><span class="line">    <span class="attr">data</span>: &#123;  <span class="attr">msg</span>: <span class="string">&quot;hello&quot;</span> &#125;,</span><br><span class="line">    <span class="attr">dataType</span>: <span class="string">&quot;jsonp&quot;</span>,</span><br><span class="line">    <span class="attr">jsonp</span>: <span class="string">&quot;callback&quot;</span>,         <span class="comment">// 回调参数 </span></span><br><span class="line">    <span class="attr">jsonpCallback</span>: <span class="string">&quot;handler&quot;</span>   <span class="comment">// jsonp 自定义回调函数  </span></span><br><span class="line">    <span class="attr">success</span>: <span class="keyword">function</span>(<span class="params">data</span>)&#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(data)</span><br><span class="line">    &#125;，</span><br><span class="line">    <span class="attr">error</span>: <span class="keyword">function</span>(<span class="params"></span>)&#123; &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="Websocket"><a href="#Websocket" class="headerlink" title="Websocket"></a>Websocket</h2><blockquote>
<p>规范定义了一种客户端和服务器之间存在持久连接的**全双工通信协议(又称双向通信)**，它没有跨域的限制但和 HTTP 都是基于 TCP 协议的应用层协议，两者有良好的兼容性但没有联系。它能更好地节省服务器资源和带宽并可以实现实时通讯。</p>
</blockquote>
<h3 id="实时通信"><a href="#实时通信" class="headerlink" title="实时通信"></a>实时通信</h3><ul>
<li><strong>Ajax 轮询</strong><ul>
<li>原理：客户端设置 计时器，每隔一段时间就向服务器发送一次请求。</li>
<li>缺点：只能由客户端发起请求，而且需要服务器有很快的 资源处理速度。</li>
</ul>
</li>
<li><strong>http 长轮询</strong><ul>
<li>原理：客户端发起请求建立连接后，服务器等到有内容更新时才响应。</li>
<li>缺点：采用阻塞模型，占用的资源空间更多而需要服务器有很高的并发处理能力。</li>
</ul>
<p>  </p>
</li>
<li><strong>WebSocket</strong>：只需要通过一个握手即可实现客户端与服务端通信，不需要询问和等待。</li>
</ul>
<h3 id="连接过程"><a href="#连接过程" class="headerlink" title="连接过程"></a>连接过程</h3><blockquote>
<p>WebSocket 在建立握手时传输数据通过 HTTP，但建立后传输时不需要 HTTP。Socket 则是应用层与 TCP&#x2F;IP 通信的中间软件抽象层，本质一组接口而并非一个协议。</p>
</blockquote>
<ol>
<li>浏览器、服务器通过 TCP 三次握手建立连接 (通信基础)。</li>
<li>浏览器通过向服务器发起一个包含 WebSocket 支持版本号等附加头信息的 HTTP 请求。</li>
<li>服务器同样采用 HTTP 协议返回应答信息。</li>
<li>当收到连接成功的信息后通过 TCP 通道进行传输通信。</li>
<li>客户端&#x2F;服务器端 关闭连接前可以自由传输数据。</li>
</ol>
  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 前端：(&#x27;WebSocket&#x27; in window) 可判断是否支持</span></span><br><span class="line"><span class="keyword">let</span> ws = <span class="keyword">new</span> <span class="title class_">WebSocket</span>(<span class="string">&#x27;ws://10.148.221.210:5000&#x27;</span>)  </span><br><span class="line">ws.<span class="property">onopen</span> = <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="comment">// 0、1、2、3 ：正在连接、连接成功、连接正在关闭、连接失败或已关闭</span></span><br><span class="line">    <span class="keyword">if</span> (socket.<span class="property">readyState</span> === <span class="number">1</span>) &#123;</span><br><span class="line">        ws.<span class="title function_">send</span>(<span class="string">&quot;connect success&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line">ws.<span class="property">onmessage</span> = <span class="keyword">function</span>(<span class="params">msg</span>)&#123; &#125;</span><br><span class="line">ws.<span class="title function_">addEventListener</span>(<span class="string">&#x27;error&#x27;</span>, <span class="keyword">function</span>(<span class="params"></span>)&#123; &#125;)</span><br><span class="line">ws.<span class="title function_">close</span>()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 后端</span></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">WebSocket</span> = <span class="built_in">require</span>(<span class="string">&quot;ws&quot;</span>);</span><br><span class="line"><span class="keyword">const</span> server = <span class="keyword">new</span> <span class="title class_">WebSocket</span>.<span class="title class_">Server</span>(&#123; <span class="attr">port</span>: <span class="number">8080</span> &#125;);</span><br><span class="line">server.<span class="title function_">on</span>(<span class="string">&quot;connection&quot;</span>, <span class="keyword">function</span>(<span class="params">socket</span>) &#123;</span><br><span class="line">    socket.<span class="title function_">on</span>(<span class="string">&quot;message&quot;</span>, <span class="keyword">function</span>(<span class="params">data</span>) &#123;</span><br><span class="line">        socket.<span class="title function_">send</span>(data);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h2 id="window-postMessage"><a href="#window-postMessage" class="headerlink" title="window.postMessage"></a>window.postMessage</h2><blockquote>
<p>采用异步方式支持跨域通信的 HTML5 API，主要功能有：页面和其打开的新窗口的数据传递、多窗口之间消息传递、页面与嵌套的 iframe 消息传递。</p>
</blockquote>
  <figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">index.html</span><br><span class="line"><span class="tag">&lt;<span class="name">iframe</span> <span class="attr">src</span>=<span class="string">&quot;http://localhost:8080&quot;</span> <span class="attr">frameborder</span>=<span class="string">&quot;0&quot;</span> <span class="attr">onload</span>=<span class="string">&quot;load()&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">iframe</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">function</span> <span class="title function_">load</span>(<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">        iframe.<span class="property">contentWindow</span>.<span class="title function_">postMessage</span>(<span class="string">&quot;笔记&quot;</span>, <span class="string">&quot;http://localhost:8080&quot;</span>);</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">window</span>.<span class="property">onmessage</span> = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="variable language_">console</span>.<span class="title function_">log</span>(e.<span class="property">data</span>);</span></span><br><span class="line"><span class="language-javascript">        &#125;;</span></span><br><span class="line"><span class="language-javascript">    &#125;</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"></span><br><span class="line">another.html</span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="variable language_">window</span>.<span class="property">onmessage</span> = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(e.<span class="property">data</span>);   <span class="comment">// 笔记</span></span></span><br><span class="line"><span class="language-javascript">        e.<span class="property">source</span>.<span class="title function_">postMessage</span>(e.<span class="property">data</span>, e.<span class="property">origin</span>);</span></span><br><span class="line"><span class="language-javascript">    &#125;;</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="document-domain-Iframe"><a href="#document-domain-Iframe" class="headerlink" title="document.domain + Iframe"></a>document.domain + Iframe</h2><blockquote>
<p>该方式只能用于二级域名相同的情况下，比如 a.test.com、b.test.com。只需要给页面添加 document.domain &#x3D;’test.com’ 表示二级域名都相同就可以实现跨域。</p>
</blockquote>
  <figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">www.   baidu.  com     .</span><br><span class="line">三级域  二级域   顶级域   根域</span><br><span class="line"></span><br><span class="line">// a.test.com</span><br><span class="line"><span class="tag">&lt;<span class="name">iframe</span> <span class="attr">src</span>=<span class="string">&quot;http://b.test.com/b.html&quot;</span> <span class="attr">frameborder</span>=<span class="string">&quot;0&quot;</span> <span class="attr">onload</span>=<span class="string">&quot;load()&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">iframe</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="variable language_">document</span>.<span class="property">domain</span> = <span class="string">&quot;test.com&quot;</span>;</span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">function</span> <span class="title function_">load</span>(<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(frame.<span class="property">contentWindow</span>.<span class="property">a</span>);</span></span><br><span class="line"><span class="language-javascript">    &#125;</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"></span><br><span class="line">// b.test.com</span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="variable language_">document</span>.<span class="property">domain</span> = <span class="string">&quot;test.com&quot;</span>;</span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">var</span> a = <span class="number">100</span>;</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="window-location-hash-Iframe"><a href="#window-location-hash-Iframe" class="headerlink" title="window.location.hash + Iframe"></a>window.location.hash + Iframe</h2><blockquote>
<p>通过一个非跨域的中间页面来传递 hash 数据：a.html –&gt; c.html –&gt; b.html –&gt; a.html。</p>
</blockquote>
  <figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">a.html</span><br><span class="line"><span class="tag">&lt;<span class="name">iframe</span> <span class="attr">src</span>=<span class="string">&quot;http://localhost:8080/hash/c.html#name1&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">iframe</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="variable language_">window</span>.<span class="property">onhashchange</span> = <span class="keyword">function</span>(<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(location.<span class="property">hash</span>);</span></span><br><span class="line"><span class="language-javascript">    &#125;;</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"></span><br><span class="line">b.html</span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="variable language_">window</span>.<span class="property">parent</span>.<span class="property">parent</span>.<span class="property">location</span>.<span class="property">hash</span> = location.<span class="property">hash</span>;</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"></span><br><span class="line">c.html</span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">const</span> iframe = <span class="variable language_">document</span>.<span class="title function_">createElement</span>(<span class="string">&quot;iframe&quot;</span>);</span></span><br><span class="line"><span class="language-javascript">    iframe.<span class="property">src</span> = <span class="string">&quot;http://localhost:8000/hash/b.html#name2&quot;</span>;</span></span><br><span class="line"><span class="language-javascript">    <span class="variable language_">document</span>.<span class="property">body</span>.<span class="title function_">appendChild</span>(iframe);</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>


<h2 id="window-name-Iframe"><a href="#window-name-Iframe" class="headerlink" title="window.name + Iframe"></a>window.name + Iframe</h2><blockquote>
<p>window.location 变化后重新加载，window.name 属性可以保持不变。具体实现：通过 iframe src 属性由外域转向本地域，跨域数据即由 iframe window.name 从外域传递到本地域。这就安全地绕过了浏览器的跨域访问限制。</p>
</blockquote>
  <figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">a.html</span><br><span class="line"><span class="tag">&lt;<span class="name">iframe</span> <span class="attr">src</span>=<span class="string">&quot;http://localhost:8080/name/c.html&quot;</span> <span class="attr">frameborder</span>=<span class="string">&quot;0&quot;</span> <span class="attr">onload</span>=<span class="string">&quot;load()&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">iframe</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">let</span> first = <span class="literal">true</span>;</span></span><br><span class="line"><span class="language-javascript">    <span class="comment">// onload 事件会触发2次，第1次加载跨域页，并留存数据于 window.name</span></span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">function</span> <span class="title function_">load</span>(<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">if</span> (first) &#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="comment">// 第1次onload(跨域页)成功后，切换到同域代理页面</span></span></span><br><span class="line"><span class="language-javascript">            iframe.<span class="property">src</span> = <span class="string">&quot;http://localhost:8000/name/b.html&quot;</span>;</span></span><br><span class="line"><span class="language-javascript">            first = <span class="literal">false</span>;</span></span><br><span class="line"><span class="language-javascript">        &#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="comment">// 第2次onload(同域b.html页)成功后，读取同域window.name中数据</span></span></span><br><span class="line"><span class="language-javascript">            <span class="variable language_">console</span>.<span class="title function_">log</span>(iframe.<span class="property">contentWindow</span>.<span class="property">name</span>);</span></span><br><span class="line"><span class="language-javascript">        &#125;</span></span><br><span class="line"><span class="language-javascript">    &#125;</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"></span><br><span class="line">b.html：中间代理页，与 a.html 同域，内容为空。</span><br><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line">c.html</span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="variable language_">window</span>.<span class="property">name</span> = <span class="string">&quot;笔记&quot;</span>;</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h1 id="四、页面操作"><a href="#四、页面操作" class="headerlink" title="四、页面操作"></a>四、页面操作</h1><h2 id="页面更新"><a href="#页面更新" class="headerlink" title="页面更新"></a>页面更新</h2>  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 刷新当前页面</span></span><br><span class="line"><span class="variable language_">window</span>.<span class="property">location</span>.<span class="title function_">reload</span>()</span><br><span class="line"><span class="variable language_">window</span>.<span class="property">location</span>.<span class="title function_">replace</span>(url)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 跳转到新页面</span></span><br><span class="line">&lt;a href=<span class="string">&quot;url&quot;</span>&gt;&lt;/a&gt;</span><br><span class="line"><span class="variable language_">window</span>.<span class="property">location</span>.<span class="property">href</span> = url</span><br><span class="line"></span><br><span class="line"><span class="comment">// 打开新页面</span></span><br><span class="line">&lt;a href=<span class="string">&quot;url&quot;</span> target=<span class="string">&quot;_blank&quot;</span>&gt;&lt;/a&gt;</span><br><span class="line"><span class="variable language_">window</span>.<span class="title function_">open</span>(url, <span class="string">&quot;_blank&quot;</span>)</span><br></pre></td></tr></table></figure>

<h2 id="文件下载"><a href="#文件下载" class="headerlink" title="文件下载"></a>文件下载</h2><blockquote>
<p>浏览器中的文件地址打不开时就会变为下载。注意 ios 页面通过 location.href 指向下载地址后会直接预览，返回时会丢失全局数据而导致页面报错，只能使用 window.open。</p>
</blockquote>
  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">// 1、location、window.open 下载文件</span></span><br><span class="line"> location.<span class="property">href</span> = <span class="string">&quot;http://baidu.com/?name=a&quot;</span></span><br><span class="line"> <span class="variable language_">window</span>.<span class="title function_">open</span>(<span class="string">&#x27;http://baidu.com/&#x27;</span>, <span class="string">&#x27;_blank&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">file_download</span> (data, fileName) &#123;</span><br><span class="line">     <span class="keyword">var</span> link = <span class="variable language_">document</span>.<span class="title function_">createElement</span>(<span class="string">&#x27;a&#x27;</span>)</span><br><span class="line">     link.<span class="property">download</span> = fileName</span><br><span class="line">     link.<span class="property">style</span>.<span class="property">display</span> = <span class="string">&#x27;none&#x27;</span></span><br><span class="line"></span><br><span class="line">     <span class="comment">// 2、通过 Blob 下载文本文件</span></span><br><span class="line">     <span class="keyword">var</span> blob = <span class="keyword">new</span> <span class="title class_">Blob</span>([data])</span><br><span class="line">     link.<span class="property">href</span> = <span class="variable language_">window</span>.<span class="property">URL</span>.<span class="title function_">createObjectURL</span>(blob)</span><br><span class="line"></span><br><span class="line">     <span class="comment">// 3、通过 base64 下载任意文件</span></span><br><span class="line">     <span class="keyword">var</span> canvas = <span class="variable language_">document</span>.<span class="title function_">createElement</span>(<span class="string">&#x27;canvas&#x27;</span>);</span><br><span class="line">     <span class="keyword">var</span> context = canvas.<span class="title function_">getContext</span>(<span class="string">&#x27;2d&#x27;</span>);</span><br><span class="line">     <span class="keyword">var</span> width = data.<span class="property">width</span>;</span><br><span class="line">     <span class="keyword">var</span> height = data.<span class="property">height</span>;</span><br><span class="line">     context.<span class="title function_">drawImage</span>(data, <span class="number">0</span>, <span class="number">0</span>);</span><br><span class="line">     link.<span class="property">href</span> = context.<span class="title function_">toDataURL</span>(<span class="string">&#x27;image/png&#x27;</span>);</span><br><span class="line"></span><br><span class="line">     <span class="variable language_">document</span>.<span class="property">body</span>.<span class="title function_">appendChild</span>(link)</span><br><span class="line">     link.<span class="title function_">click</span>()</span><br><span class="line">     <span class="variable language_">document</span>.<span class="property">body</span>.<span class="title function_">removeChild</span>(link)</span><br><span class="line">     <span class="variable language_">window</span>.<span class="property">URL</span>.<span class="title function_">revokeObjectURL</span>(link.<span class="property">href</span>)</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>


<h2 id="PDF-预览"><a href="#PDF-预览" class="headerlink" title="PDF 预览"></a>PDF 预览</h2><blockquote>
<p>通过标签直接加载的方案都是将 pdf 内容全部下载完成之后才开始渲染，文件较大时需要用户等待很长时间，为了实现高性能的在线预览则需要实现分片加载。</p>
</blockquote>
  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 基于 PDF.js 库进行深度定制</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@title</span> 1、下载分片：通过服务器获取分片 url 并下载</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@prame</span> loadStatus：保存加载状态 (等待、已下载)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@prame</span> pages：保存已经下载的分片</span></span><br><span class="line"><span class="comment">***/</span></span><br><span class="line"><span class="keyword">const</span> loadStatus = &#123; <span class="attr">WAIT</span>: <span class="number">0</span>, <span class="attr">LOADED</span>: <span class="number">1</span> &#125;</span><br><span class="line"><span class="keyword">const</span> &#123; startPage, totalPage, url &#125; = <span class="keyword">await</span> <span class="title function_">fetchPdfFragment</span>(<span class="number">1</span>);</span><br><span class="line"><span class="keyword">const</span> pages = <span class="title function_">initPages</span>(totalPage);</span><br><span class="line"><span class="keyword">const</span> loadingTask = <span class="variable constant_">PDFJS</span>.<span class="title function_">getDocument</span>(url);</span><br><span class="line">loadingTask.<span class="property">promise</span>.<span class="title function_">then</span>(<span class="function">(<span class="params">pdfDoc</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; pdfDoc.<span class="property">numPages</span>; i += <span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">const</span> pageIndex = startPage + i;</span><br><span class="line">        <span class="keyword">const</span> page = pages[pageIndex - <span class="number">1</span>];</span><br><span class="line">        <span class="keyword">if</span> (page.<span class="property">loadStatus</span> !== loadStatus.<span class="property">LOADED</span>) &#123;</span><br><span class="line">            pdfDoc.<span class="title function_">getPage</span>(i + <span class="number">1</span>).<span class="title function_">then</span>(<span class="function">(<span class="params">pdfPage</span>) =&gt;</span> &#123;</span><br><span class="line">                page.<span class="property">pdfPage</span> = pdfPage;</span><br><span class="line">                page.<span class="property">loadStatus</span> = loadStatus.<span class="property">LOADED</span>;</span><br><span class="line">                <span class="title function_">startRenderPages</span>();</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">initPages</span> (totalPage) &#123;</span><br><span class="line">    <span class="keyword">const</span> pages = [];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; totalPage; i += <span class="number">1</span>) &#123;</span><br><span class="line">        pages.<span class="title function_">push</span>(&#123;</span><br><span class="line">            <span class="attr">pageNo</span>: i + <span class="number">1</span>, </span><br><span class="line">            <span class="attr">dom</span>: <span class="literal">null</span>, </span><br><span class="line">            <span class="attr">pdfPage</span>: <span class="literal">null</span>,</span><br><span class="line">            <span class="attr">loadStatus</span>: loadStatus.<span class="property">WAIT</span></span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 2、渲染分片</span></span><br><span class="line"><span class="keyword">const</span> viewport = pdfPage.<span class="title function_">getViewport</span>(&#123; <span class="attr">scale</span>: <span class="number">1</span>, <span class="attr">rotation</span>: <span class="number">0</span> &#125;);</span><br><span class="line"><span class="keyword">const</span> pageSize = &#123; <span class="attr">width</span>: viewport.<span class="property">width</span>, <span class="attr">height</span>: viewport.<span class="property">height</span> &#125;</span><br><span class="line"><span class="keyword">const</span> contentView = <span class="variable language_">document</span>.<span class="title function_">createElement</span>(<span class="string">&#x27;div&#x27;</span>);</span><br><span class="line">contentView.<span class="property">style</span>.<span class="property">width</span> = <span class="string">`<span class="subst">$&#123;<span class="variable language_">this</span>.pageSize.width&#125;</span>px`</span>;</span><br><span class="line">contentView.<span class="property">style</span>.<span class="property">height</span> = <span class="string">`<span class="subst">$&#123;(totalPage * (pageSize.height + <span class="number">10</span>))&#125;</span>px`</span>;</span><br><span class="line">pdfContainer.<span class="title function_">appendChild</span>(contentView);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 根据 pdf 的页码来将其内容渲染到指定区域</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">renderPageContent</span> (page) &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; pdfPage, pageNo, dom &#125; = page;</span><br><span class="line">    <span class="keyword">if</span> (dom) &#123; <span class="keyword">return</span> &#125;</span><br><span class="line">    <span class="keyword">const</span> viewport = pdfPage.<span class="title function_">getViewport</span>(&#123; <span class="attr">scale</span>: <span class="number">1</span>, <span class="attr">rotation</span>: <span class="number">0</span> &#125;);</span><br><span class="line">    <span class="keyword">const</span> canvas = <span class="variable language_">document</span>.<span class="title function_">createElement</span>(<span class="string">&#x27;canvas&#x27;</span>);</span><br><span class="line">    <span class="keyword">const</span> context = canvas.<span class="title function_">getContext</span>(<span class="string">&#x27;2d&#x27;</span>);</span><br><span class="line">    canvas.<span class="property">height</span> = pageSize.<span class="property">height</span>;</span><br><span class="line">    canvas.<span class="property">width</span> = pageSize.<span class="property">width</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> pageDom = <span class="variable language_">document</span>.<span class="title function_">createElement</span>(<span class="string">&#x27;div&#x27;</span>);</span><br><span class="line">    pageDom.<span class="property">style</span>.<span class="property">position</span> = <span class="string">&#x27;absolute&#x27;</span>;</span><br><span class="line">    pageDom.<span class="property">style</span>.<span class="property">top</span> = <span class="string">`<span class="subst">$&#123;((pageNo - <span class="number">1</span>) * (pageSize.height + <span class="number">10</span>))&#125;</span>px`</span>;</span><br><span class="line">    pageDom.<span class="property">style</span>.<span class="property">width</span> = <span class="string">`<span class="subst">$&#123;pageSize.width&#125;</span>px`</span>;</span><br><span class="line">    pageDom.<span class="property">style</span>.<span class="property">height</span> = <span class="string">`<span class="subst">$&#123;pageSize.height&#125;</span>px`</span>;</span><br><span class="line">    pageDom.<span class="title function_">appendChild</span>(canvas);</span><br><span class="line">  </span><br><span class="line">    pdfPage.<span class="title function_">render</span>(&#123; <span class="attr">canvasContext</span>: context, viewport &#125;);</span><br><span class="line">    page.<span class="property">dom</span> = pageDom;</span><br><span class="line">    contentView.<span class="title function_">appendChild</span>(pageDom);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 滚动加载：监听滚动触发 scrollPdf，防抖保证不会一次产生过多请求</span></span><br><span class="line">scrollPdf = _.<span class="title function_">debounce</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> scrollTop = pdfContainer.<span class="property">scrollTop</span>;</span><br><span class="line">    <span class="keyword">const</span> height = pdfContainer.<span class="property">height</span>;</span><br><span class="line">    <span class="comment">// 根据内容可视区域中心点计算页码, 没有滚动时，指向第一页</span></span><br><span class="line">    <span class="keyword">const</span> index = <span class="title class_">Math</span>.<span class="title function_">ceil</span>((scrollTop + height/<span class="number">2</span>) / (pageSize.<span class="property">height</span> + <span class="number">10</span>));</span><br><span class="line">    <span class="keyword">const</span> pageIndex = scrollTop &gt; <span class="number">0</span> ? index : <span class="number">1</span>;</span><br><span class="line">    <span class="title function_">loadBefore</span>(pageIndex);</span><br><span class="line">    <span class="title function_">loadAfter</span>(pageIndex);</span><br><span class="line">&#125;, <span class="number">200</span>)</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">loadBefore</span> (pageIndex) &#123;  <span class="comment">// 获取当前页之前页面的分片</span></span><br><span class="line">    <span class="comment">// 假定每个分片的大小是 5 页</span></span><br><span class="line">    <span class="keyword">const</span> start = (<span class="title class_">Math</span>.<span class="title function_">floor</span>(pageIndex/<span class="number">5</span>) * <span class="number">5</span>) - (<span class="number">5</span> - <span class="number">1</span>);</span><br><span class="line">    <span class="keyword">if</span> (start &gt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">const</span> prevPage = pages[start - <span class="number">1</span>] || &#123;&#125;;</span><br><span class="line">        prevPage.<span class="property">loadStatus</span> ===loadStatus.<span class="property">WAIT</span> &amp;&amp; <span class="title function_">loadPdfData</span>(start);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">loadAfter</span> (pageIndex) &#123;  <span class="comment">// 获取当前页之后页面的分片</span></span><br><span class="line">    <span class="keyword">const</span> start = (<span class="title class_">Math</span>.<span class="title function_">floor</span>(pageIndex/<span class="number">5</span>) * <span class="number">5</span>) + <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">if</span> (start &lt;= pages.<span class="property">length</span>) &#123;</span><br><span class="line">        <span class="keyword">const</span> nextPage = pages[start - <span class="number">1</span>] || &#123;&#125;;</span><br><span class="line">        nextPage.<span class="property">loadStatus</span> ===loadStatus.<span class="property">WAIT</span> &amp;&amp; <span class="title function_">loadPdfData</span>(start);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 3、性能优化：文件页数过多时一直滚动渲染可能导致页面卡顿，需要清除可视范围外的页面元素。</span></span><br><span class="line"><span class="comment">// 获取需要渲染的范围</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">getRenderScope</span> (pageIndex) &#123;</span><br><span class="line">    <span class="keyword">const</span> pagesToRender = [];</span><br><span class="line">    <span class="keyword">let</span> i = pageIndex - <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">let</span> j = pageIndex + <span class="number">1</span>;</span><br><span class="line">    pagesToRender.<span class="title function_">push</span>(pages[pageIndex - <span class="number">1</span>]);</span><br><span class="line">    <span class="comment">// 根据当前的可视范围内的页码，我们前后只保留 10 页</span></span><br><span class="line">    <span class="keyword">while</span> (pagesToRender.<span class="property">length</span> &lt; <span class="number">10</span> &amp;&amp; pagesToRender.<span class="property">length</span> &lt; pages.<span class="property">length</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (i &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            pagesToRender.<span class="title function_">push</span>(pages[i - <span class="number">1</span>]);</span><br><span class="line">            i -= <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (pagesToRender.<span class="property">length</span> &gt;= <span class="number">10</span>) &#123;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (j &lt;= pages.<span class="property">length</span>) &#123;</span><br><span class="line">            pagesToRender.<span class="title function_">push</span>(<span class="variable language_">this</span>.<span class="property">pages</span>[j - <span class="number">1</span>]);</span><br><span class="line">            j += <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> pagesToRender;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 渲染需要展示的页面，不需展示的页码将其清除</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">renderPages</span> (pageIndex) &#123;</span><br><span class="line">    <span class="keyword">const</span> pagesToRender = <span class="title function_">getRenderScope</span>(pageIndex);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> i <span class="keyword">of</span> pages) &#123;</span><br><span class="line">        <span class="keyword">if</span> (pagesToRender.<span class="title function_">includes</span>(i)) &#123;</span><br><span class="line">            i.<span class="property">loadStatus</span> === loadStatus.<span class="property">LOADED</span> ? </span><br><span class="line">            <span class="title function_">renderPageContent</span>(i) : <span class="title function_">renderPageLoading</span>(）;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="title function_">clearPage</span>(i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 清除页面 dom</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">clearPage</span> (page) &#123;</span><br><span class="line">    <span class="keyword">if</span> (page.<span class="property">dom</span>) &#123;</span><br><span class="line">       contentView.<span class="title function_">removeChild</span>(page.<span class="property">dom</span>);</span><br><span class="line">       page.<span class="property">dom</span> = <span class="literal">undefined</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 页面正在下载时渲染 loading 视图</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">renderPageLoading</span> (page) &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; pageNo, dom &#125; = page;</span><br><span class="line">    <span class="keyword">if</span> (dom) &#123; <span class="keyword">return</span>; &#125;</span><br><span class="line">    <span class="keyword">const</span> pageDom = <span class="variable language_">document</span>.<span class="title function_">createElement</span>(<span class="string">&#x27;div&#x27;</span>);</span><br><span class="line">    pageDom.<span class="property">style</span>.<span class="property">width</span> = <span class="string">`<span class="subst">$&#123;pageSize.width&#125;</span>px`</span>;</span><br><span class="line">    pageDom.<span class="property">style</span>.<span class="property">height</span> = <span class="string">`<span class="subst">$&#123;pageSize.height&#125;</span>px`</span>;</span><br><span class="line">    pageDom.<span class="property">style</span>.<span class="property">position</span> = <span class="string">&#x27;absolute&#x27;</span>;</span><br><span class="line">    pageDom.<span class="property">style</span>.<span class="property">top</span> = <span class="string">`<span class="subst">$&#123;((pageNo - <span class="number">1</span>) * (pageSize.height + <span class="number">10</span>))&#125;</span>px`</span>;</span><br><span class="line">    <span class="comment">// 此处在 dom 上添加 loading 组件，省略实现</span></span><br><span class="line">    page.<span class="property">dom</span> = pageDom;</span><br><span class="line">    contentView.<span class="title function_">appendChild</span>(pageDom);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="文件上传"><a href="#文件上传" class="headerlink" title="文件上传"></a>文件上传</h2>  <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1、表单上传</span></span><br><span class="line">&lt;form action=<span class="string">&quot;/save&quot;</span> method=<span class="string">&quot;post&quot;</span> enctype=<span class="string">&quot;multipart/form-data&quot;</span>&gt;</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;file&quot;</span> <span class="attr">class</span>=<span class="string">&quot;file&quot;</span> <span class="attr">name</span>=<span class="string">&quot;file&quot;</span> /&gt;</span></span></span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">&quot;submit&quot;</span> <span class="attr">class</span>=<span class="string">&quot;btn&quot;</span>&gt;</span>上传<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">&quot;button&quot;</span> <span class="attr">class</span>=<span class="string">&quot;btn&quot;</span>&gt;</span>上传<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line">&lt;/form&gt;</span><br><span class="line">$(<span class="string">&#x27;#form&#x27;</span>).<span class="title function_">ajaxSubmit</span>(&#123;</span><br><span class="line">    <span class="attr">success</span>: <span class="keyword">function</span> (<span class="params">res</span>) &#123; &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2、模拟表单数据上传</span></span><br><span class="line">&lt;input id=<span class="string">&quot;fileinfo&quot;</span> type=<span class="string">&quot;file&quot;</span> <span class="keyword">class</span>=<span class="string">&quot;file&quot;</span> /&gt;</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">&quot;button&quot;</span> <span class="attr">class</span>=<span class="string">&quot;upload&quot;</span>&gt;</span>上传<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="keyword">var</span> formData = <span class="keyword">new</span> <span class="title class_">FormData</span>();</span><br><span class="line">formData.<span class="title function_">append</span>(<span class="string">&quot;files&quot;</span>, $(<span class="string">&quot;.notFormFile&quot;</span>)[<span class="number">0</span>].<span class="property">files</span>[<span class="number">0</span>])</span><br><span class="line">$.<span class="title function_">ajax</span>(&#123;</span><br><span class="line">    <span class="attr">url</span>: <span class="string">&quot;save&quot;</span>,</span><br><span class="line">    <span class="attr">type</span>: <span class="string">&quot;POST&quot;</span>,</span><br><span class="line">    <span class="attr">data</span>: formData,</span><br><span class="line">    <span class="attr">processData</span>: <span class="literal">false</span>,           <span class="comment">// 不处理发送数据</span></span><br><span class="line">    <span class="attr">contentType</span>: <span class="literal">false</span>,           <span class="comment">// 不设置 Content-Type</span></span><br><span class="line">    <span class="attr">success</span>: <span class="keyword">function</span> (<span class="params">res</span>) &#123; &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 3、分片上传</span></span><br><span class="line">&lt;input type=<span class="string">&quot;file&quot;</span> id=<span class="string">&quot;file&quot;</span> multiple&gt;</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">&quot;button&quot;</span> <span class="attr">class</span>=<span class="string">&quot;btn&quot;</span>&gt;</span>分片上传<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="keyword">let</span> files = $(<span class="string">&#x27;#file&#x27;</span>)[<span class="number">0</span>].<span class="property">files</span></span><br><span class="line"><span class="title function_">upload</span>(files[<span class="number">0</span>], <span class="number">0</span>);</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">upload</span> (file, skip) &#123;</span><br><span class="line">    <span class="keyword">var</span> formData = <span class="keyword">new</span> <span class="title class_">FormData</span>();</span><br><span class="line">    <span class="keyword">var</span> blockSize = <span class="number">1000000</span>;</span><br><span class="line">    <span class="keyword">var</span> nextSize = <span class="title class_">Math</span>.<span class="title function_">min</span>((skip + <span class="number">1</span>) * blockSize, file.<span class="property">size</span>);             </span><br><span class="line">    <span class="keyword">var</span> fileData = file.<span class="title function_">slice</span>(skip * blockSize, nextSize);</span><br><span class="line">    formData.<span class="title function_">append</span>(<span class="string">&quot;file&quot;</span>, fileData);</span><br><span class="line">    formData.<span class="title function_">append</span>(<span class="string">&quot;fileName&quot;</span>, file.<span class="property">name</span>);</span><br><span class="line">    $.<span class="title function_">ajax</span>(&#123;</span><br><span class="line">        <span class="attr">url</span>: <span class="string">&quot;/save&quot;</span>,</span><br><span class="line">        <span class="attr">type</span>: <span class="string">&quot;POST&quot;</span>,</span><br><span class="line">        <span class="attr">data</span>: formData,</span><br><span class="line">        <span class="attr">processData</span>: <span class="literal">false</span>,</span><br><span class="line">        <span class="attr">contentType</span>: <span class="literal">false</span>,</span><br><span class="line">        <span class="attr">success</span>: <span class="keyword">function</span> (<span class="params">res</span>) &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">`已上传<span class="subst">$&#123;skip+<span class="number">1</span>&#125;</span>`</span>)</span><br><span class="line">            <span class="keyword">if</span> (file.<span class="property">size</span> &lt;= nextSize) &#123;</span><br><span class="line">                <span class="title function_">alert</span>(<span class="string">&quot;上传完成&quot;</span>)</span><br><span class="line">                <span class="keyword">return</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="title function_">upload</span>(file, ++skip)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 4、拖拽、粘贴上传：ondrop、onpaste</span></span><br><span class="line">&lt;textarea placeholder=<span class="string">&quot;请将文件拖拽或直接粘贴到这里&quot;</span>&gt;&lt;/textarea&gt;</span><br><span class="line">$(<span class="string">&quot;textarea&quot;</span>).<span class="property">ondrop</span> = <span class="keyword">function</span> (<span class="params">event</span>) &#123;</span><br><span class="line">    event.<span class="title function_">preventDefault</span>();</span><br><span class="line">    <span class="comment">// 拖拽数据</span></span><br><span class="line">    <span class="keyword">var</span> file = event.<span class="property">dataTransfer</span>.<span class="property">files</span>[<span class="number">0</span>];</span><br><span class="line">    <span class="comment">// 粘贴数据</span></span><br><span class="line">    <span class="keyword">var</span> clipboard = event.<span class="property">clipboardData</span>.<span class="property">items</span>[<span class="number">0</span>];</span><br><span class="line">    <span class="keyword">if</span> (clipboard.<span class="property">kind</span> == <span class="string">&#x27;file&#x27;</span> || </span><br><span class="line">        clipboard.<span class="property">type</span>.<span class="title function_">indexOf</span>(<span class="string">&#x27;image&#x27;</span>) &gt; -<span class="number">1</span>) &#123;</span><br><span class="line">        file = clipboard.<span class="title function_">getAsFile</span>()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> formData = <span class="keyword">new</span> <span class="title class_">FormData</span>();</span><br><span class="line">    formData.<span class="title function_">append</span>(<span class="string">&quot;files&quot;</span>, files);</span><br><span class="line">    $.<span class="title function_">ajax</span>(&#123;</span><br><span class="line">        <span class="attr">url</span>: <span class="string">&quot;/save&quot;</span>,</span><br><span class="line">        <span class="attr">type</span>: <span class="string">&quot;POST&quot;</span>,</span><br><span class="line">        <span class="attr">data</span>: formData,</span><br><span class="line">        <span class="attr">processData</span>: <span class="literal">false</span>,</span><br><span class="line">        <span class="attr">contentType</span>: <span class="literal">false</span>,</span><br><span class="line">        <span class="attr">success</span>: <span class="keyword">function</span> (<span class="params">res</span>) &#123; &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>




    </div>

    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;margin-top:20px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>chuangges
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://chuangges.gitee.io/2019/05/28/4-5-js%E4%BA%A4%E4%BA%92/" title="JS 实现页面的通信和交互">https://chuangges.gitee.io/2019/05/28/4-5-js交互/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh_CN" rel="external nofollow noopener noreferrer" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2019/05/23/4-5-ES%E8%AF%AD%E6%B3%95/" rel="prev" title="ES6 ～ ES9 新特性">
      <i class="fa fa-chevron-left"></i> ES6 ～ ES9 新特性
    </a></div>
      <div class="post-nav-item">
    <a href="/2019/06/01/4-6-js%E7%BC%96%E7%A8%8B/" rel="next" title="JS 编程范式">
      JS 编程范式 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1"><span class="nav-number">1.</span> <span class="nav-text">一、网络通信</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BD%91%E7%BB%9C%E6%A8%A1%E5%9E%8B"><span class="nav-number">1.1.</span> <span class="nav-text">网络模型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#TCP-x2F-UDP-%E5%8D%8F%E8%AE%AE"><span class="nav-number">1.2.</span> <span class="nav-text">TCP&#x2F;UDP 协议</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#HTTP-%E5%8D%8F%E8%AE%AE"><span class="nav-number">1.3.</span> <span class="nav-text">HTTP 协议</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Socket-%E6%8E%A5%E5%8F%A3"><span class="nav-number">1.4.</span> <span class="nav-text">Socket 接口</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81Ajax-%E8%AF%B7%E6%B1%82"><span class="nav-number">2.</span> <span class="nav-text">二、Ajax 请求</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%BB%E8%A6%81%E7%89%B9%E7%82%B9"><span class="nav-number">2.1.</span> <span class="nav-text">主要特点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%87%8D%E7%82%B9%E6%B3%A8%E6%84%8F"><span class="nav-number">2.2.</span> <span class="nav-text">重点注意</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AF%B7%E6%B1%82%E6%96%B9%E5%BC%8F"><span class="nav-number">2.2.1.</span> <span class="nav-text">请求方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%95%B0%E6%8D%AE%E6%A0%BC%E5%BC%8F"><span class="nav-number">2.2.2.</span> <span class="nav-text">数据格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AF%B7%E6%B1%82%E4%BD%93%E7%B1%BB%E5%9E%8B"><span class="nav-number">2.2.3.</span> <span class="nav-text">请求体类型</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8"><span class="nav-number">2.3.</span> <span class="nav-text">简单使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8E%9F%E7%94%9F%E5%86%99%E6%B3%95"><span class="nav-number">2.3.1.</span> <span class="nav-text">原生写法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Ajax-%E5%B0%81%E8%A3%85"><span class="nav-number">2.3.2.</span> <span class="nav-text">Ajax 封装</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#JQuery-%E5%86%99%E6%B3%95"><span class="nav-number">2.3.3.</span> <span class="nav-text">JQuery 写法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Token-%E4%BB%A4%E7%89%8C"><span class="nav-number">2.4.</span> <span class="nav-text">Token 令牌</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E8%B7%A8%E5%9F%9F%E6%96%B9%E6%A1%88"><span class="nav-number">3.</span> <span class="nav-text">三、跨域方案</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#CORS-%E8%B7%A8%E5%9F%9F%E8%B5%84%E6%BA%90%E5%85%B1%E4%BA%AB"><span class="nav-number">3.1.</span> <span class="nav-text">CORS 跨域资源共享</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Node-%E6%AD%A3%E5%90%91%E4%BB%A3%E7%90%86"><span class="nav-number">3.2.</span> <span class="nav-text">Node 正向代理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#cli-%E5%B7%A5%E5%85%B7"><span class="nav-number">3.2.1.</span> <span class="nav-text">cli 工具</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#cors-anywhere"><span class="nav-number">3.2.2.</span> <span class="nav-text">cors-anywhere</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#charles"><span class="nav-number">3.2.3.</span> <span class="nav-text">charles</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Nginx-%E5%8F%8D%E5%90%91%E4%BB%A3%E7%90%86"><span class="nav-number">3.3.</span> <span class="nav-text">Nginx 反向代理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JSONP"><span class="nav-number">3.4.</span> <span class="nav-text">JSONP</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Websocket"><span class="nav-number">3.5.</span> <span class="nav-text">Websocket</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%9E%E6%97%B6%E9%80%9A%E4%BF%A1"><span class="nav-number">3.5.1.</span> <span class="nav-text">实时通信</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BF%9E%E6%8E%A5%E8%BF%87%E7%A8%8B"><span class="nav-number">3.5.2.</span> <span class="nav-text">连接过程</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#window-postMessage"><span class="nav-number">3.6.</span> <span class="nav-text">window.postMessage</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#document-domain-Iframe"><span class="nav-number">3.7.</span> <span class="nav-text">document.domain + Iframe</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#window-location-hash-Iframe"><span class="nav-number">3.8.</span> <span class="nav-text">window.location.hash + Iframe</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#window-name-Iframe"><span class="nav-number">3.9.</span> <span class="nav-text">window.name + Iframe</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9B%9B%E3%80%81%E9%A1%B5%E9%9D%A2%E6%93%8D%E4%BD%9C"><span class="nav-number">4.</span> <span class="nav-text">四、页面操作</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%A1%B5%E9%9D%A2%E6%9B%B4%E6%96%B0"><span class="nav-number">4.1.</span> <span class="nav-text">页面更新</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%96%87%E4%BB%B6%E4%B8%8B%E8%BD%BD"><span class="nav-number">4.2.</span> <span class="nav-text">文件下载</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#PDF-%E9%A2%84%E8%A7%88"><span class="nav-number">4.3.</span> <span class="nav-text">PDF 预览</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0"><span class="nav-number">4.4.</span> <span class="nav-text">文件上传</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="chuangges" src="" data-original="/images/chuang.png">
  <p class="site-author-name" itemprop="name">chuangges</p>
  <div class="site-description" itemprop="description">chuangge's blog.</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">39</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/chuangges" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;chuangges" rel="external nofollow noopener noreferrer" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://stackoverflow.com/yourname" title="StackOverflow → https:&#x2F;&#x2F;stackoverflow.com&#x2F;yourname" rel="external nofollow noopener noreferrer" target="_blank"><i class="fab fa-stack-overflow fa-fw"></i>StackOverflow</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://juejin.im/" title="https:&#x2F;&#x2F;juejin.im&#x2F;" rel="external nofollow noopener noreferrer" target="_blank">掘金</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://www.nowcoder.com/" title="https:&#x2F;&#x2F;www.nowcoder.com&#x2F;" rel="external nofollow noopener noreferrer" target="_blank">牛客网</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://www.docschina.org/" title="https:&#x2F;&#x2F;www.docschina.org&#x2F;" rel="external nofollow noopener noreferrer" target="_blank">印记中文</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="http://tool.lu/" title="http:&#x2F;&#x2F;tool.lu&#x2F;" rel="external nofollow noopener noreferrer" target="_blank">在线工具</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://tinypng.com/" title="https:&#x2F;&#x2F;tinypng.com&#x2F;" rel="external nofollow noopener noreferrer" target="_blank">图片压缩</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://bigjpg.com/" title="https:&#x2F;&#x2F;bigjpg.com&#x2F;" rel="external nofollow noopener noreferrer" target="_blank">图片放大</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://tool.chinaz.com/" title="https:&#x2F;&#x2F;tool.chinaz.com&#x2F;" rel="external nofollow noopener noreferrer" target="_blank">站长工具</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://learn-anything.xyz/" title="https:&#x2F;&#x2F;learn-anything.xyz&#x2F;" rel="external nofollow noopener noreferrer" target="_blank">Learn-Anything</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://stackoverflow.com/" title="https:&#x2F;&#x2F;stackoverflow.com&#x2F;" rel="external nofollow noopener noreferrer" target="_blank">Stack-Overflow</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">chuangge</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">1m</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">15:14</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="external nofollow noopener noreferrer" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="external nofollow noopener noreferrer" target="_blank">NexT.Pisces</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","model":{"jsonPath":"/live2dw/assets/tororo.model.json"},"display":{"position":"left","width":180,"height":360},"mobile":{"show":false},"react":{"opacityDefault":1,"opacityOnHover":1},"log":false,"tagMode":false});</script>
        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(e){e.imageLazyLoadSetting.processImages=t;var n=e.imageLazyLoadSetting.isSPA,i=e.imageLazyLoadSetting.preloadRatio||1,r=o();function o(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){n&&(r=o());for(var t,a=0;a<r.length;a++)0<=(t=(t=r[a]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(e.innerHeight*i||document.documentElement.clientHeight*i)&&function(){var t,e,n,i,o=r[a];e=function(){r=r.filter(function(t){return o!==t})},(t=o).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,t.removeAttribute("data-original"),e&&e()},t.src!==i&&(n.src=i))}()}function a(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",a),e.addEventListener("resize",a),e.addEventListener("orientationchange",a)}(this);</script></body>
</html>
